$(function() {
	
	// ************************* 初始化 ********************/
//	initQueryPanel();
//	initGrid();
	autoInitGrid();
	initDialogForm();
//	windowChange();
	
	//  ********************* 查询面板 ****************/
	function initQueryPanel() {
		$("#queryPanel").show();
		
		$("#query_form").anzeForm({
			simpleMsg: true,
			submitHandler : function() {
				$("#book").anzeQuery({postData: {filters: getFilters()}});
			}
		});
		
		$("#query_form").anzeQueryPanel({onExpand : function () {
			$("#book").reSize();
		}, onCollapse : function () {
			$("#book").reSize();
		}});
	}
	
	// ********************* jqGrid ****************/
	function initGrid() { // 手动生成Grid
		var isComplete = false;
		var config = 
			{
				url: appPath +"/query",
				datatype: "json", 
				mtype: "POST",
				height: "100%",
			    loadui: "block",
				toolbar: [true, "top"],
				altRows: true,
				altclass: "altClass",
				autowidth: true,
				shrinkToFit: false,//true:列宽自适应
				viewrecords: true,
				multiselect: true,
				sortable: true,
			    prmNames : { nd : null},
				jsonReader: { repeatitems : false },
				rowNum: 10,
				rowList: [ 10, 20, 50 ],
				sortname:"id",
				sortorder:"desc",
				pager: "#bookMask",
				postData: { type:"jqGrid", mark:"book" },
				colModel:[{name:"id", label: "ID", index:"id", hidden:true, hidedlg : true},
						{name:"name", label: "图书名", index:"name", width:150, align:"center"},
						{name:"author", label: "著作者", index:"author", width:150, align:"center",
				   			edittype:"select",editoptions:{value:"明月:我是明月;星星:我是星;"},
							formatter:"select"},
						{name:"price", label: "单价", index:"price", width:100, align:"center", sorttype:"number", formatter:"number",
							formatoptions:{decimalPlaces: 2},
							cellattr: function(rowId, val, rawObject, cm, rdata) {
								var style = "style='";
								if (rawObject.price<50) {
									style += "color:red;";
								}
								if (rawObject.price>=50) {
									style += "color:blue;";
								}
								style += "'";
								return style;
							}},
						{name:"description", label: "描述", index:"description", width:300},
						{name:"create_timestamp", label: "创建时间", index:"create_timestamp", width:140, align:"center",
							formatter:"date", formatoptions : {newformat : "yyyy-MM-dd HH:mm:ss"}
						}],
				beforeRequest: function() {
					$("#book").setGridHeight($("#bookMask"), 58, 400);
					$("#book").setGridWidth();
					$("#book").reSize();
					$("#jqgh_book_cb .cbox").hide();
					
					if (!isComplete) {
						isComplete = true;
						return false;
					}
				},
		        loadError: function(xhr, status, error) {
		        	$("#book").reSize();
		        	$.anze.errorHandle(xhr, status, error);
		        },
				loadComplete: function(data) {
		        	$("#book").reSize();
		        },
				beforeSelectRow: function(rowid, e) {
					var selectIds = $(this).jqGrid("getGridParam", "selarrrow");
					for (var i = 0; i < selectIds.length; i++) {
						if (rowid != selectIds[i]) {
							$(this).jqGrid("setSelection", selectIds[i]);
						}
					}
					return true;
				}
			};
		$("#book").jqGrid(config);
		$("#book").jqGrid("navGrid", "#bookMask", {edit: false, add: false, del: false, search: false, refresh: false});
		$("#book").anzeAddTool({buttons : [{sn : "0101030101", name : "新增"}, {sn : "0101030102", name : "编辑"}, {sn : "0101030103", name : "删除"}]})
			.anzeQueryButton({form: "#query_form"}).anzeExportButton({getFilters : getFilters});
		$("#book").jqGrid("navButtonAdd", "#bookMask", { caption: "", buttonicon: "ui-icon-refresh",
			position: "last", title: "刷新", cursor: "pointer",
			onClickButton: function () {
				$("#book").anzeQuery();
			}});
		$("#0101030101").button().click(add);
		$("#0101030102").button().click(edit);
		$("#0101030103").button().click(del);
		
		// 完成后查询
		$("#query_form").submit();
	}
	
	function autoInitGrid() { // 自动生成Grid
		// 2.1中的方式，废弃
/*		$("#book").anzeJqGrid({
			mark : "book",
			pager : "#bookMask",
			heightOffset : [58, 400],
			widthOffset : [0, 0],
			sortname : "id",
			sortorder : "desc",
			buttons : [{sn : "0101030101"}, {sn : "0101030102"}, {sn : "0101030103"}],
			queryComponent : "#queryPanel",
			queryForm : "#query_form",
			getFilters : getFilters,
//			colModel : [{label: "ID", name:"id", index:"id", hidden:false, hidedlg : false},
//					{label: "Name", name:"name", index:"name", width:150, align:"center"},
//					{label: "Author", name:"author", index:"author", width:150, align:"center",
//			   			edittype:"select",editoptions:{value:"明月:我是明月;星星:我是星;"},
//						formatter:"select"},
//					{},{},{},
//					{label: "AAAA", name:"", index:"create_timestamp", width:140, align:"center",
//							formatter: function () {
//								return "AAAAA";
//							}}],
			onButtonsInited : function () {
				$("#0101030101").click(add);
				$("#0101030102").click(edit);
				$("#0101030103").click(del);
			}
		});*/
		//2.2方式
		$("#bookQuery").anzeCq({
			mark : "book",
			heightOffset : [58, 400],
			sortname : "id",
			sortorder : "desc",
//			rowList : [ 5, 10 ],
//			rowNum : 5,
//			checkButtons : false,
			buttons : [{sn : "0101030101"}, {sn : "0101030102"}, {sn : "0101030103"}],
//			queryComponent : "#queryPanel", //没有 queryComponent 或 queryForm 参数，将自动生成查询面板
//			queryForm : "#query_form",
//			getFilters : getFilters, //没有此参数，将自动生成查询表达式
//			colModel : [{label: "ID", name:"id", index:"id", hidden:false, hidedlg : false},
//					{label: "Name", name:"name", index:"name", width:150, align:"center"},
//					{label: "Author", name:"author", index:"author", width:150, align:"center",
//			   			edittype:"select",editoptions:{value:"明月:我是明月;星星:我是星;"},
//						formatter:"select"},
//					{},{},{},
//					{label: "AAAA", name:"", index:"create_timestamp", width:140, align:"center",
//							formatter: function () {
//								return "AAAAA";
//							}}],
			onButtonsInited : function () {
				$("#0101030101").click(add);
				$("#0101030102").click(edit);
				$("#0101030103").click(del);
			},
			queryOptions : {afterReset : function() {
				//
			}}
		});
	}

	// ************************ 表单对话框 *******************/
	var $formDia, $name, $author, $price, $description;
	function initDialogForm() {
		$formDia = $("#book-dialog-form").anzeFormDialog({
			simpleMsg : true,
			bindEnter : false
		});

		$name = $("#form1 #name");
		$author = $("#form1 #author");
		$price = $("#form1 #price");
		$description = $("#form1 #description");
	}

	// ************************* 其它处理 ********************/

	/**
	 * 新增
	 */
	function add() {
		$formDia.anzeFormDialog({
			title : "新增",
			open : function(validator) {
				validator.resetForm();
			},
			beforeSubmit : function($form, options) {
				options.url = bookPath + "/add";
				return true;
			},
			onReset : function(validator) {
				validator.resetForm();
			},
			onSuccess : function() {
				$.anze.info("新增成功！");
				$("#book").anzeQuery();
			},
			onError : function(jqXHR, textStatus, errorThrown) {
				if (!$.anze.errorHandle(jqXHR, textStatus, errorThrown)) {
					$.anze.error("新增失败！");
				}
			}
		});
		$formDia.dialog("open");
	}

	/**
	 * 编辑
	 */
	function edit() {
		var rowid = $("#book").jqGrid("getGridParam", "selarrrow");
		if (rowid == null || rowid.length != 1) {
			$.anze.warn("请选择一条数据！");
			return;
		}
		var row = $("#book").jqGrid("getRowData", rowid[0]);

		$formDia.anzeFormDialog({
			title : "编辑",
			open : function(validator) {
				validator.resetForm();
				$name.val(row.name);
				$author.val(row.author);
				$price.val(row.price);
				$description.val(row.description);
			},
			beforeSubmit : function($form, options) {
				options.url = bookPath + "/" + row.id;
				options.data = { "_method" : "PUT" };
				return true;
			},
			onReset : function(validator) {
				validator.resetForm();
				$name.val(row.name);
				$author.val(row.author);
				$price.val(row.price);
				$description.val(row.description);
			},
			onSuccess : function() {
				$.anze.info("编辑成功！");
				$("#book").anzeQuery();
			},
			onError : function(jqXHR, textStatus, errorThrown) {
				if (!$.anze.errorHandle(jqXHR, textStatus, errorThrown)) {
					$.anze.error("编辑失败！");
				}
			}
		});
		$formDia.dialog("open");

	}

	/**
	 * 删除
	 */
	function del() {
		var rowid = $("#book").jqGrid("getGridParam", "selarrrow");
		if (rowid == null || rowid.length != 1) {
			$.anze.warn("请选择一条数据！");
			return;
		}
		if ($.anze.confirm("删除", "您确定要删除选中的记录吗？", function() {
			$.anze.ajax({
				url : bookPath + "/" + rowid[0],
				type : "POST",
				data : {
					"_method" : "DELETE"
				},
				success : function(data) {
					$.anze.info("删除成功！");
					$("#book").anzeQuery();
				},
				error : function(jqXHR, textStatus, errorThrown, handled) {
					if (!handled) {
						$.anze.error("删除失败！");
					}
				}
			});
		}));
	}

	/**
	 * 查询条件
	 */
	function getFilters() {
		var name = $("#query_form #name").val();
		var author = $("#query_form #author").val();
		var price = $("#query_form #price").val();
		
		var queryFilters ="{'groupOp':'AND','rules':[";
		var filter;
		if(name != ""){
			filter = "{'field':'name','op':'cn','data':'"+ name +"'},";
			queryFilters = queryFilters.concat(filter);
		}
		if(author != ""){
			filter = "{'field':'author','op':'cn','data':'"+ author +"'},";
			queryFilters = queryFilters.concat(filter);
		}
		if(price != ""){
			filter = "{'field':'price','op':'eq','data':'"+ price +"'},";
			queryFilters = queryFilters.concat(filter);
		}
		if("," == queryFilters.charAt(queryFilters.length - 1)){
			queryFilters = queryFilters.substr(0, queryFilters.length - 1);
		}
		queryFilters = queryFilters.concat("]}");
		
		return queryFilters;
	}

	// ******************** 注册窗口变化时事件 ********************/
	function windowChange() {
		$(window).resize(function() {
			// 设置Grid高度和宽度
//			$("#book").reSize();
		});
	}
	
});

// 演示显示格式参数（FORMAT_OPTIONS）的99方式的{fun:"getValue"}参数
function getValue(value, options, rData) {
	return value + "1";
}

//演示其它属性（ATTRS）的99方式的{fun:"getStyle"}参数
function getStyle(rowId, val, rawObject, cm, rdata) {
    var style = "style='";
    if (rawObject.price<50) {
        style += "color:red;";
    }
    if (rawObject.price>=50) {
        style += "color:blue;";
    }
    style += "'";
    return style;
}
